/*
 * GeneratorUtil.java 1.00 2008. 01. 21
 * 
 * Copyright (c) 2008 David.Kim(KJS). All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of
 * David.Kim(KJS). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you
 * entered into with David.Kim(KJS).
 */
package doit.gen.util;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import doit.framework.util.SharedMethods;
import doit.gen.domain.Column;

/**
 * <pre>
 * system      : 공통
 * menu        : 공통
 * source      : GeneratorUtil.java
 * description : 제너레이터 관련 유틸리티
 * </pre>
 * 
 * @version <pre>
 * 1.0	2008. 01. 21  leewan  최초 작성
 * 1.1
 * </pre>
 */

@SuppressWarnings("unchecked")

public class GeneratorUtil {

    /**
     * 디렉토리 생성 makeDirectorys :
     * 
     * @param parentDir
     * @param childDir
     * @return
     */
    public static boolean makeDirectorys(String parentDir, String childDir) {
        boolean _result = true;
        try {
            File directory = new File(parentDir, childDir);
            if (!directory.exists())
                directory.mkdir();
        } catch (Exception e) {
            e.printStackTrace();
            _result = false;
        }
        return _result;
    }

    /**
     * 디렉토리 삭제 deleteDirectorys :
     * 
     * @param parentDir
     * @param childDir
     * @return
     */
    public static boolean deleteDirectorys(String parentDir, String childDir) {
        boolean _result = true;
        try {
            File directory = new File(parentDir, childDir);
            deleteAllFile(directory);
        } catch (Exception e) {
            e.printStackTrace();
            _result = false;
        }
        return _result;
    }

    /**
     * 디렉토리 파일 삭제 deleteAllFile :
     * 
     * @param file
     */
    public static void deleteAllFile(File file) {
        File[] fileList = file.listFiles();
        if (fileList != null && fileList.length != 0) {
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    deleteAllFile(fileList[i]);
                } else {
                    fileList[i].delete();
                }
            }
        }
        file.delete();
    }

    /**
     * 파일 생성 makeFile :
     * 
     * @param fullFileName
     * @return
     */
    public static File makeFile(String fullFileName) {
        File genFile = null;
        try {
            genFile = new File(fullFileName);
            if (!genFile.exists()) {
                genFile.createNewFile();
            } else {
                genFile.delete();
                genFile.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return genFile;
    }

    /**
     * 테이블에 해당하는 클래스 이름 리턴 getClassName :
     * 
     * @param tableName
     * @return
     */
    public static String getClassName(String tableName) {
        if (tableName == null || tableName.length() <= 0)
            return "";

//        String[] arrClassName = tableName.toLowerCase().substring(tableName.indexOf("_") > 0 ? tableName.indexOf("_") + 1 : 0).split("_");
        String[] arrClassName = tableName.toLowerCase().split("_");

        String className = "";
        for (int i = 0; i < arrClassName.length; i++)
            className += arrClassName[i].substring(0, 1).toUpperCase() + arrClassName[i].substring(1, arrClassName[i].length());

        return className;
    }

    /**
     * 테이블 컬럼에 해당하는 필드 이름 리턴 getFieldName :
     * 
     * @param columnName
     * @return
     */
    public static String getFieldName(String columnName) {
        if (columnName == null)
            return "";

        String[] arrFieldName = columnName.toLowerCase().split("_");

        String fieldName = "";
        for (int i = 0; i < arrFieldName.length; i++) {
            if (i == 0)
                fieldName += arrFieldName[i];
            else
                fieldName += arrFieldName[i].substring(0, 1).toUpperCase() + arrFieldName[i].substring(1, arrFieldName[i].length());
        }
        return fieldName;
    }

    /**
     * 테이블 컬럼에 해당하는 필드 이름 리턴 getFieldName :
     * 
     * @param className
     * @return
     */
    public static String getArgumentName(String className) {
        if (className == null)
            return "";

        return className.substring(0, 1).toLowerCase() + className.substring(1, className.length());
    }

    /**
     * 테이블 컬럼에 해당하는 getter 메소드 이름 리턴 getMethodName :
     * 
     * @param columnName
     * @return
     */
    public static String getMethodName(String columnName) {
        if (columnName == null)
            return "";

        String[] arrFieldName = columnName.toLowerCase().split("_");

        String methodName = "get";
        for (int i = 0; i < arrFieldName.length; i++) {
            methodName += arrFieldName[i].substring(0, 1).toUpperCase() + arrFieldName[i].substring(1, arrFieldName[i].length());
        }
        return methodName;
    }

    /**
     * 테이블 컬럼에 해당하는 setter 메소드 이름 리턴 setMethodName :
     * 
     * @param columnName
     * @return
     */
    public static String setMethodName(String columnName) {
        if (columnName == null)
            return "";

        String[] arrFieldName = columnName.toLowerCase().split("_");

        String methodName = "set";
        for (int i = 0; i < arrFieldName.length; i++) {
            methodName += arrFieldName[i].substring(0, 1).toUpperCase() + arrFieldName[i].substring(1, arrFieldName[i].length());
        }
        return methodName;
    }

    /**
     * 테이블 컬럼에 해당하는 필드 형식 리턴 getVariableType :
     * 
     * @param column
     * @return
     * @throws Exception
     */
    public static String getVariableType(Column column) throws Exception {
        String variableType = null;
        if (column.getDataType().equals("VARCHAR") || column.getDataType().equals("VARCHAR2") || column.getDataType().equals("BLOB") || column.getDataType().equals("CLOB") || column.getDataType().equals("DATE") || column.getDataType().equals("CHAR")) {
            variableType = "String";
        } else if (column.getDataType().equals("NUMBER")) {
            if (column.getDataScale() > 0) {
                variableType = "Double";
            } else {
                if (column.getDataLength() > 5) {
                    variableType = "long";
                } else {
                    variableType = "int";
                }
            }
        }

        return variableType;
    }

    /**
     * 테이블 컬럼에 해당하는 필드 형식에 맞는 초기값 리턴 getVariableInitial :
     * 
     * @param column
     * @return
     * @throws Exception
     */
    public static String getVariableInitial(Column column) throws Exception {
        String initialize = null;
        if (column.getDataType().equals("VARCHAR") || column.getDataType().equals("VARCHAR2") || column.getDataType().equals("BLOB") || column.getDataType().equals("CLOB") || column.getDataType().equals("DATE") || column.getDataType().equals("CHAR")) {
            initialize = "\"\"";
        } else if (column.getDataType().equals("NUMBER")) {
            if (column.getDataScale() > 0) {
                initialize = "0.0";
            } else {
                initialize = "0";
            }
        }

        return initialize;
    }

    /**
     * RandomAccessFile 쓰기 write :
     * 
     * @param raf
     * @param line
     * @throws Exception
     */
    public static void write(RandomAccessFile raf, String line) throws Exception {
        raf.write((line).getBytes("UTF-8"));
    }

    /**
     * RandomAccessFile 쓰기 writeln :
     * 
     * @param raf
     * @param line
     * @throws Exception
     */
    public static void writeln(RandomAccessFile raf, String line) throws Exception {
        raf.write((line + "\r\n").getBytes("UTF-8"));
    }

    /**
     * 라이선스 정보 printLicense :
     * 
     * @param className
     * @return
     */
    public static String printLicense(String className) {
        StringBuffer sb = new StringBuffer();
        sb.append("/* ").append("\n");
        sb.append(" * " + className + ".java		1.00	" + SharedMethods.getDate("yyyy-MM-dd") + " ").append("\n");
        sb.append(" *").append("\n");
        sb.append(" * Copyright (c) " + SharedMethods.getDate("yyyy") + " " + System.getProperties().get("user.name") + ". All Rights Reserved.").append("\n");
        sb.append(" * ").append("\n");
        sb.append(" * This software is the confidential and proprietary information").append("\n");
        sb.append(" * of " + System.getProperties().get("user.name") + ".  You shall not disclose such Confidential Information").append("\n");
        sb.append(" * and shall use it only in accordance with the terms of the license agreement").append("\n");
        sb.append(" * you entered into with " + System.getProperties().get("user.name") + ".").append("\n");
        sb.append(" */").append("\n");

        return sb.toString();
    }

    /**
     * 라이선스 정보
     * 
     * @param className
     * @param fileType
     * @return
     */
    public static String printLicense(String className, String fileType) {
        StringBuffer sb = new StringBuffer();
        sb.append("/* ").append("\n");
        sb.append(" * " + className + "." + fileType + "		1.00	" + SharedMethods.getDate("yyyy-MM-dd") + " ").append("\n");
        sb.append(" *").append("\n");
        sb.append(" * Copyright (c) " + SharedMethods.getDate("yyyy") + " " + System.getProperties().get("user.name") + ". All Rights Reserved.").append("\n");
        sb.append(" * ").append("\n");
        sb.append(" * This software is the confidential and proprietary information").append("\n");
        sb.append(" * of " + System.getProperties().get("user.name") + ".  You shall not disclose such Confidential Information").append("\n");
        sb.append(" * and shall use it only in accordance with the terms of the license agreement").append("\n");
        sb.append(" * you entered into with " + System.getProperties().get("user.name") + ".").append("\n");
        sb.append(" */").append("\n");

        return sb.toString();
    }

    /**
     * 패키지 명 printPackage :
     * 
     * @param packageName
     * @return
     */
    public static String printPackage(String packageName) {
        return "package " + packageName + ";\n\n";
    }

    /**
     * 자바독 printJavaDoc :
     * 
     * @param className
     * @return
     */
    public static String printJavaDoc(String className, String systemName, String menuName, String menuDesc) {
        StringBuffer sb = new StringBuffer();
        sb.append("/**").append("\n");
        sb.append(" * <pre>").append("\n");
        sb.append(" * system      : " + systemName).append("\n");
        sb.append(" * menu        : " + menuName).append("\n");
        sb.append(" * source      : " + className + ".java").append("\n");
        sb.append(" * description : " + menuDesc).append("\n");
        sb.append(" * </pre> ").append("\n");
        sb.append(" * @version").append("\n");
        sb.append(" * <pre> ").append("\n");
        sb.append(" * 1.0	" + SharedMethods.getDate("yyyy-MM-dd") + " created by " + System.getProperties().get("user.name")).append("\n");
        sb.append(" * 1.1	").append("\n");
        sb.append(" * </pre>").append("\n");
        sb.append(" */").append("\n");
        sb.append("\n");
        sb.append("@SuppressWarnings(\"unchecked\")").append("\n");
        sb.append("\n");

        return sb.toString();
    }

    /**
     * 항목 중 PK만을 꺼내온다.
     * @param columns
     * @return
     */
    public static List getPkList( List columns) {

        List pkList = new ArrayList();
        for (int i = 0; i < columns.size(); i++)
            if (((Column) columns.get(i)).getPrimaryYn().equals("Y"))
                pkList.add(columns.get(i));

        return pkList;
    }

    /**
     * 마지막 PK항목을 가져온다.
     * @param columns
     * @return
     */
    public static Column getlastPkColumn( List columns) {

        List pkList = getPkList( columns);

        return (Column)pkList.get( pkList.size()-1);
    }
}
